package com.gzu.finalwork.admin.service;

import com.gzu.finalwork.admin.mapper.SensitiveOperationLogMapper;
import com.gzu.finalwork.entity.admin.SensitiveOperationLog;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 敏感操作日志服务类
 */
@Service
public class SensitiveOperationLogService {

    private static final Logger logger = LoggerFactory.getLogger(SensitiveOperationLogService.class);

    @Autowired
    private SensitiveOperationLogMapper sensitiveOperationLogMapper;

    /**
     * 异步记录敏感操作日志
     * @param log 日志对象
     */
    @Async
    public void recordLog(SensitiveOperationLog log) {
        try {
            if (log.getCreatedAt() == null) {
                log.setCreatedAt(LocalDateTime.now());
            }
            sensitiveOperationLogMapper.insertLog(log);
            logger.debug("敏感操作日志记录成功: {}", log.getOperationDesc());
        } catch (Exception e) {
            logger.error("记录敏感操作日志失败: {}", e.getMessage(), e);
        }
    }

    /**
     * 根据ID查询日志
     * @param id 日志ID
     * @return 日志对象
     */
    public SensitiveOperationLog getLogById(Long id) {
        try {
            return sensitiveOperationLogMapper.selectById(id);
        } catch (Exception e) {
            logger.error("查询敏感操作日志失败: {}", e.getMessage(), e);
            return null;
        }
    }

    /**
     * 分页查询敏感操作日志
     * @param pageNum 页码
     * @param pageSize 每页大小
     * @param operationType 操作类型（可选）
     * @param operatorUsername 操作人用户名（可选）
     * @param startTime 开始时间（可选）
     * @param endTime 结束时间（可选）
     * @return 分页结果
     */
    public Map<String, Object> getLogsByPage(int pageNum, int pageSize,
                                           String operationType, String operatorUsername,
                                           LocalDateTime startTime, LocalDateTime endTime) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 计算偏移量
            int offset = (pageNum - 1) * pageSize;
            
            // 查询数据
            List<SensitiveOperationLog> logs = sensitiveOperationLogMapper.selectByPage(
                    offset, pageSize, operationType, operatorUsername, startTime, endTime);
            
            // 查询总数
            int total = sensitiveOperationLogMapper.countLogs(operationType, operatorUsername, startTime, endTime);
            
            result.put("list", logs);
            result.put("total", total);
            result.put("pageNum", pageNum);
            result.put("pageSize", pageSize);
            result.put("pages", (int) Math.ceil((double) total / pageSize));
            
        } catch (Exception e) {
            logger.error("分页查询敏感操作日志失败: {}", e.getMessage(), e);
            result.put("list", List.of());
            result.put("total", 0);
            result.put("pageNum", pageNum);
            result.put("pageSize", pageSize);
            result.put("pages", 0);
        }
        return result;
    }

    /**
     * 清理指定时间之前的日志
     * @param beforeTime 时间点
     * @return 清理的日志数量
     */
    public int cleanLogsBefore(LocalDateTime beforeTime) {
        try {
            int deletedCount = sensitiveOperationLogMapper.deleteBeforeTime(beforeTime);
            logger.info("清理敏感操作日志成功，清理数量: {}", deletedCount);
            return deletedCount;
        } catch (Exception e) {
            logger.error("清理敏感操作日志失败: {}", e.getMessage(), e);
            return 0;
        }
    }

    /**
     * 获取日志统计信息
     * @return 统计信息
     */
    public Map<String, Object> getLogStatistics() {
        Map<String, Object> stats = new HashMap<>();
        try {
            // 今日日志数
            LocalDateTime todayStart = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0).withNano(0);
            LocalDateTime todayEnd = todayStart.plusDays(1);
            int todayCount = sensitiveOperationLogMapper.countLogs(null, null, todayStart, todayEnd);
            
            // 本周日志数
            LocalDateTime weekStart = todayStart.minusDays(todayStart.getDayOfWeek().getValue() - 1);
            int weekCount = sensitiveOperationLogMapper.countLogs(null, null, weekStart, null);
            
            // 本月日志数
            LocalDateTime monthStart = todayStart.withDayOfMonth(1);
            int monthCount = sensitiveOperationLogMapper.countLogs(null, null, monthStart, null);
            
            // 总日志数
            int totalCount = sensitiveOperationLogMapper.countLogs(null, null, null, null);
            
            stats.put("todayCount", todayCount);
            stats.put("weekCount", weekCount);
            stats.put("monthCount", monthCount);
            stats.put("totalCount", totalCount);
            
        } catch (Exception e) {
            logger.error("获取敏感操作日志统计失败: {}", e.getMessage(), e);
            stats.put("todayCount", 0);
            stats.put("weekCount", 0);
            stats.put("monthCount", 0);
            stats.put("totalCount", 0);
        }
        return stats;
    }
} 